﻿using System.Buffers;
using System.Text;

string alphabet = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя ";

// Количество триграм
List<List<List<int>>> countTrigrams = [];

// Десятичный логарифм количества триграм
List<List<List<double>>> logCountTrigrams = [];

int allCountTrigrams = 0;


for (int i = 0; i < 34; i++)
{
    countTrigrams.Add(new List<List<int>>(34));
    logCountTrigrams.Add(new List<List<double>>(34));

    for (int j = 0; j < 34; j++)
    {
        countTrigrams[i].Add(new List<int>(34));
        logCountTrigrams[i].Add(new List<double>(34));

        for (int k = 0; k < 34; k++)
        {
            countTrigrams[i][j].Add(0);
            logCountTrigrams[i][j].Add(0);

        }

    }
}

using FileStream fileText = new("C:\\Users\\khabi\\OneDrive\\Рабочий стол\\Programming\\Programs on C#\\Сryptography\\CalculatingTrigrams\\dostoevski.txt", FileMode.Open, FileAccess.Read);


int bytes = 1024;
byte[] bufferRead = new byte[bytes];

string Aij = "@#$";
while (fileText.Read(bufferRead, 0, bytes) > 0)
{
    string str = (System.Text.Encoding.UTF8.GetString(bufferRead)).ToLower();

    Aij = Aij[2].ToString() + str[0] + str[1];

    for (int i = 2; i < str.Length; i++)
    {
        Aij = Aij[1].ToString() + Aij[2].ToString() + str[i];
        if (alphabet.Contains(Aij[0]) && alphabet.Contains(Aij[1]) && alphabet.Contains(Aij[2]))
        {
            countTrigrams[alphabet.IndexOf(Aij[0])][alphabet.IndexOf(Aij[1])][alphabet.IndexOf(Aij[2])]++;
            allCountTrigrams++;
        }
    }
}

using FileStream fileCryptoText = new("C:\\Users\\khabi\\OneDrive\\Рабочий стол\\Programming\\Programs on C#\\Сryptography\\CalculatingTrigrams\\D_rezult.txt", FileMode.Open, FileAccess.Write);

// Таблица логарифмов количества
var builder = new StringBuilder();
builder.Append("Таблица логарифмов от количества триграмм\n");

for (int i = 0; i < countTrigrams.Count; i++)
{
    // Первый уровень
    builder.Append($"/*Буква ({alphabet[i]})*/\n\t\tnew List<double[]>()\n\t\t{{\n");

    for (int j = 0; j < countTrigrams[i].Count; j++)
    {
        // Второй уровень
        builder.Append("\t\t\tnew double[] {\t");

        for (int k = 0; k < countTrigrams[i][j].Count; k++)
        {
            if (countTrigrams[i][j][k] > 0)
            {
                logCountTrigrams[i][j][k] = Math.Log(countTrigrams[i][j][k], 10);
            }
            builder.Append(logCountTrigrams[i][j][k].ToString("F2", System.Globalization.CultureInfo.GetCultureInfo("en-US")) + ",\t");
        }

        builder.Append("},\n");
    }

    builder.Append("\t\t},\n");
}

byte[] bufferWrite = System.Text.Encoding.UTF8.GetBytes(builder.ToString());
fileCryptoText.Write(bufferWrite, 0, bufferWrite.Length);
